package web

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	_ "web-example/web/route"
)

const (
	subPath = "./web"
)

func WriteFile(w http.ResponseWriter, pattern string) {
	data, err := ioutil.ReadFile(pattern)

	if err != nil {
		log.Printf("%s", err.Error())
	}

	w.WriteHeader(200)
	w.Write(data)
}

func IndexHandler(w http.ResponseWriter, r *http.Request) {
	pattern := r.URL.Path
	fmt.Println("pattern: " + pattern)

	if pattern == "/" {
		WriteFile(w, subPath+"./index.html")
	} else if pattern[0:4] == "/api" {
		// 路由表
		//w.Write([]byte("Hello Client!"))
		fmt.Println("Hello API!")
	} else {
		fmt.Println("path:" + r.RequestURI)
		WriteFile(w, subPath+r.RequestURI)
	}
}

func StartWeb(pattern string) {
	http.HandleFunc("/", IndexHandler)
	http.ListenAndServe(pattern, nil)
}
